#include <stdio.h>
#include "main.h"
#include "mem.h"
#include "uart.h"
#include "funcBlock.h"
#include "funcBlock_OSZILLATOR.h"
#include "timer.h"

struct fb_OSZILLATOR
{
	uint8_t type;
	function_t func;
	uint8_t SEL;
	uint8_t Q;
	uint8_t TL;
	uint8_t TH;
	uint8_t state;
	int8_t Tidx;
};

// ****************** FunctionBlock NOT 1xIn 1xOut *******************

void function_fb_OSZILLATOR(struct funcBlock_t *_fb)
{
	struct fb_OSZILLATOR *fb = (struct fb_OSZILLATOR*)_fb;

	if (fb->Tidx < 0)
		return;

	switch(fb->state)
	{
		case 0:
			timer.ms[fb->Tidx] = getBusValue_16b(fb->TL);
			setState(fb->Q, 0);
			fb->state = 1;
			break;
		case 1:
			if (timer.ms[fb->Tidx] == 0)
			{
				timer.ms[fb->Tidx] = getBusValue_16b(fb->TH);
				setState(fb->Q, 1);
				fb->state = 2;
			}
			break;
		case 2:
			if (timer.ms[fb->Tidx] == 0)
			{
				fb->state = 0;
			}
			break;
	}

	//setState(fb->out0, !getState(fb->in0));
}

struct funcBlock_t* get_fb_OSZILLATOR(uint8_t SEL, uint8_t Q, uint8_t TL, uint8_t TH, int8_t Tidx)
{
	struct fb_OSZILLATOR *fb = NULL;

	if (((TL < NUM_16BIT_BUS) || (TL == NOT_CONNECTED)) &&
		((TH < NUM_16BIT_BUS) || (TH == NOT_CONNECTED)))
	{
		fb = (struct fb_OSZILLATOR*)getMem(sizeof(struct fb_OSZILLATOR));
		if (fb != NULL)
		{
			//uart_puts("OSZILLATOR\n");
			fb->type = FB_TYPE_OSZILLATOR;
			fb->func = function_fb_OSZILLATOR;
			fb->state = 0;
			fb->SEL = SEL;
			fb->Q = Q;
			fb->TL = TL;
			fb->TH = TH;
			fb->Tidx = Tidx;
		}
	}
	return (struct funcBlock_t*)fb;
}
